package member

import (
	"math"
	"parking-lot-go-dingding/controller"
	"parking-lot-go-dingding/model/cars"
	"parking-lot-go-dingding/model/view"
	"time"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	requestStruct := struct {
		AccountState string `json:"account_state"`
		AccountType  string `json:"account_type"`
		Keywords     string `json:"keywords"`
		Limit        int    `json:"limit"`
		Page         int    `json:"page"`
		SortType     int    `json:"sort_type"`
		SortParams   string `json:"sort_params"`
	}{}

	//接收加密串
	if err := c.ShouldBindJSON(&requestStruct); err != nil {
		controller.Fail(c, "json接收失败"+err.Error())
		return
	}

	start := (requestStruct.Page - 1) * requestStruct.Limit
	var memberembersDingtalkViewStruct view.MembersDingtalkViewStruct
	memberList, count, err := memberembersDingtalkViewStruct.SearchAndCount(requestStruct.AccountType, requestStruct.AccountState, requestStruct.Keywords, requestStruct.SortParams, requestStruct.SortType, start, requestStruct.Limit)
	if err != nil {
		controller.Fail(c, "会员查询失败"+err.Error())
		return
	}

	var carsStruct cars.CarsStruct

	memberReturn := make([]map[string]interface{}, 0)
	for _, v := range memberList {

		//查询车辆总数
		carCount, err := carsStruct.MemberCarCount(v.MemberId)
		if err != nil {
			controller.Fail(c, "车辆总数查询失败"+err.Error())
			return
		}

		//查询车牌
		carNumberFind, err := carsStruct.FirstByMemberId(v.MemberId)

		accountState := "正常"
		if v.MemberState == 2 {
			accountState = "禁用"
		}

		if v.MemberMoney <= 0 {
			accountState = "欠费"
		}

		if v.MemberExpiresTime.Before(time.Now()) {
			accountState = "过期"
		}

		memberType := "固定会员"
		if v.MemberType == "2" {
			memberType = "临时停车"
		}

		memberReturn = append(memberReturn, map[string]interface{}{
			"id":            v.MemberId,
			"mobile":        v.MemberMobile,
			"real_name":     v.MemberRealName,
			"expires_time":  v.MemberExpiresTime,
			"state":         v.MemberState,
			"money":         v.MemberMoney,
			"cars_nums":     carCount,
			"cars_number":   carNumberFind.CarNumber,
			"account_state": accountState,
			"member_type":   memberType,
		})
	}

	controller.Success(c, map[string]interface{}{
		"list":         memberReturn,
		"current_page": requestStruct.Page,
		"last_page":    math.Ceil(float64(count) / float64(requestStruct.Limit)),
	})
}
